package com.cema.manage.common.utils;


import cn.hutool.core.date.DateUtil;
import com.cema.manage.project.enums.RedisEnum;
import com.cema.manage.redis.RedisService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * Created by ls on 2018/6/14.
 */
@Component
public class QiniuSimpleUpload {
    @Value("${qiniu.ACCESS_KEY}")
    public String ACCESS_KEY;
    @Value("${qiniu.SECRET_KEY}")
    public String SECRET_KEY;
    @Value("${qiniu.bucketname}")
    public String bucketname;
    @Value("${qiniu.ym}")
    private String getPath;

    @Resource
    private RedisService redisService;

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return getAuth().uploadToken(bucketname);
    }

    public Auth getAuth() {
        //密钥配置
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        return auth;
    }

    public String upload(byte[] date, String key) throws IOException {
        try {
            Response res = getUploadManager().put(date, key, getUpToken());
            //打印返回的信息
            return res.bodyString();
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                return r.bodyString();
            } catch (QiniuException e1) {
                return "{hash:" + "" + ",key:" + "" + "}";
            }
        }
    }

    public UploadManager getUploadManager() {
        Configuration configuration = new Configuration();
        //创建上传对象
        UploadManager uploadManager = new UploadManager(configuration);
        return uploadManager;
    }

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        String uuidStr = str.replace("-", "");
        return uuidStr;
    }
}
